<template>
  <div class="container-fluid p-4">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-journal-check text-primary me-3"></i>
            <div>
              <div class="text-muted">我的考核</div>
              <h4 class="mb-0">{{ totalAssessments }}</h4>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-person-check text-success me-3"></i>
            <div>
              <div class="text-muted">总参与人次</div>
              <h4 class="mb-0">{{ totalParticipants }}</h4>
            </div>
          </div>
        </el-card>
      </el-col>
      <!-- <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-question-circle text-warning me-3"></i>
            <div>
              <div class="text-muted">我的题库</div>
              <h4 class="mb-0">{{ totalQuestions }}</h4>
            </div>
          </div>
        </el-card>
      </el-col> -->
      <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-file-earmark-plus text-warning me-3"></i>
            <div>
              <div class="text-muted">待发布考核</div>
              <h4 class="mb-0">{{ draftCount }}</h4>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-graph-up text-info me-3"></i>
            <div>
              <div class="text-muted">平均通过率</div>
              <h4 class="mb-0">{{ averagePassRate }}%</h4>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选和操作 -->
    <el-card class="box-card mb-4" shadow="never">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="考核名称">
          <el-input v-model="searchForm.name" placeholder="请输入考核名称"></el-input>
        </el-form-item>
        <el-form-item label="考核类型">
          <el-select v-model="searchForm.type" placeholder="请选择考核类型" style="width: 100px">
            <el-option label="全部" value=""></el-option>
            <el-option label="理论考核" value="理论考核"></el-option>
            <el-option label="实操考核" value="实操考核"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考核状态">
          <el-select v-model="searchForm.status" placeholder="请选择考核状态" style="width: 90px">
            <el-option label="全部" value=""></el-option>
            <el-option label="草稿" value="draft"></el-option>
            <el-option label="进行中" value="ongoing"></el-option>
            <el-option label="已结束" value="ended"></el-option>
            <el-option label="已发布" value="published"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
          <el-button type="primary" @click="handleCreate">创建考核</el-button>
          <!-- <el-table :data="exams" v-loading="loading" style="width: 100%">
            <el-table-column label="操作" width="180">
              <template #default="{ row }">
                <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(row.exam.id)">
                  删除
                </el-button>
              </template>
</el-table-column>
</el-table> -->
          <!-- <el-button type="info" @click="modalController.openPopup('questionBankModal')">我的题库
          </el-button> -->
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 考核列表 -->
    <el-row>
      <el-col :span="24">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h5>考核列表</h5>
            </div>
          </template>
          <!-- 1. 将 :data 直接绑定到从 store 中获取的 exams -->
          <!-- 2. 添加 v-loading 指令，用于显示加载动画 -->
          <el-table :data="exams" v-loading="loading" style="width: 100%"
            :default-sort="{ prop: 'exam.createTime', order: 'descending' }" stripe>
            <el-table-column prop="exam.title" label="考核名称" width="180">
              <template #default="scope">
                <el-link type="primary" @click="navigateToQuestions(scope.row.exam.id)">
                  {{ scope.row.exam.title }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column prop="examSection.name" label="类型" width="120"></el-table-column>
            <el-table-column prop="exam.status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.exam.status)">{{ row.exam.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="exam.createTime" label="创建日期" width="180">
              <template #default="{ row }">
                {{ formatDate(row.exam.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="exam.startTime" label="开始时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.exam.startTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="exam.endTime" label="结束时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.exam.endTime) }}
              </template>
            </el-table-column>


            <!-- 操作列 -->
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                <el-button size="small" type="primary" @click="navigateToSubmissions(row.exam.id)">阅卷</el-button>
                <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 3. 分页逻辑直接与 store 和 API 调用关联 -->
          <el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="pageSize"
            :total="examStore.total" layout="prev, pager, next, jumper" background
            class="mt-4 justify-content-center"></el-pagination>
        </el-card>
      </el-col>
    </el-row>
  </div>

  <NewAssessmentModal v-model="modalController.popups.newAssessmentModal" :exam-data="examToEdit"
    @refresh="refreshTable" />
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from "element-plus";
import { modalControllers } from "@/stores/modalController.js";
import NewAssessmentModal from "@/components/alert/teacher/NewAssessmentModal.vue";
import { onMounted } from 'vue';
import { useUserStore } from "@/stores/user.js";
import { useExamStore } from '@/stores/exam.js';
import { storeToRefs } from 'pinia';
import { useCourseStore } from '@/stores/course.js';
// 在 setup 函数顶部实例化
const courseStore = useCourseStore();
const router = useRouter();
const modalController = modalControllers();
const examStore = useExamStore();
const userStore = useUserStore();
userStore.selectTeacherCourse(userStore.user.id);
userStore.selectTeacherExam("李老师");
const examToEdit = ref(null);
// 从 store 中获取响应式的考核列表和加载状态
const { exams, loading, teacherExams,draftCount } = storeToRefs(examStore);
const totalParticipants = ref(0);
// 组件加载时，获取第一页的考核数据
onMounted(() => {
  examStore.fetchCurrentTeacherExams((data, total) => {
    // 在成功回调中，用返回的 total 字段更新我们的变量
    totalParticipants.value = total;
    calculateAndSetPassRate();
  })
    ;
  // 确保 user.name 有值
  if (userStore.user && userStore.user.name) {
    console.log("userStore.user.name:", userStore.user.name);
    examStore.fetchExams({ pageNum: 1, pageSize: 10, creatorName: userStore.user.name });
    examStore.fetchDraftCount({ status: 'draft', creatorName: userStore.user.name });
  }
  userStore.selectTeacherCourse(userStore.user.id);
});
watch(exams, (newExamsList) => {
  // 确保列表不为空
  if (newExamsList && newExamsList.length > 0) {
    checkAndSyncAssessmentStatuses(newExamsList);
  }
}, {
  deep: true, // 使用深度侦听，确保列表内部对象变化也能被捕获
  // immediate: true // 如果需要在组件初次加载时就立即检查一次，可以取消此行注释
});
// 处理“创建考核”按钮点击
const handleCreate = () => {
  examToEdit.value = null; // 清空编辑状态
  modalController.openPopup('newAssessmentModal')
};

const navigateToGradeSubmission = () => {
  const submissionId = 20; // 设置固定的ID
  router.push(`/grade-submission/${submissionId}`);
};
const navigateToSubmissions = (examId) => {
  if (!examId) {
    ElMessage.error("无效的考核ID");
    return;
  }
  router.push(`/exam/${examId}/submissions`);
};
const checkAndSyncAssessmentStatuses = (assessmentList) => {
  console.log("开始检查并同步考核状态...");
  const now = new Date(); // 获取当前时间

  assessmentList.forEach(assessment => {
    const exam = assessment.exam;

    // 只检查非“草稿”状态的考核
    if (exam.status !== 'draft') {
      const startTime = new Date(exam.startTime);
      const endTime = new Date(exam.endTime);
      let expectedStatus = exam.status; // 假设当前状态是正确的

      // 根据时间判断考核应有的状态
      if (now > endTime) {
        expectedStatus = 'ended';
      } else if (now >= startTime) {
        expectedStatus = 'ongoing';
      } else {
        expectedStatus = 'published';
      }

      // 如果计算出的应有状态和当前状态不一致，则发起更新请求
      if (exam.status !== expectedStatus) {
        console.warn(`考核 "${exam.title}" 状态不一致 (当前: ${exam.status}, 应为: ${expectedStatus})，正在发起同步...`);

        // 构造更新接口需要的完整 payload
        const payload = {
          examSectionName: assessment.examSection.name,
          //courseName: exam.courseName, // 假设 exam 对象中有 courseName 字段
          title: exam.title,
          description: exam.description,
          startTime: formatDate(exam.startTime), // 使用已有函数格式化日期
          endTime: formatDate(exam.endTime),
          status: expectedStatus // 使用最新计算出的状态
        };

        // 调用 store 中的 updateExam action
        examStore.updateExam(exam.id, payload, () => {
          console.log(`考核 "${exam.title}" 状态已成功同步为 ${expectedStatus}`);
          // 可以在成功后静默更新或重新获取列表，这里暂时只打印日志
        });
      }
    }
  });
};

const handleEdit = async (row) => {
  try {
    // 1. 先获取考核详情
    const examDetailsResponse = await new Promise((resolve, reject) => {
      examStore.fetchExamById(row.exam.id, resolve, reject);
    });

    const examData = examDetailsResponse.exam;

    if (!examData || !examData.courseId) {
      ElMessage.error("考核数据不完整，缺少课程ID。");
      return;
    }

    // 2. 根据 courseId 获取课程详情
    const courseData = await courseStore.fetchCourseDetail(examData.courseId);

    // 3. 合并数据，为模态框准备最终数据对象
    examToEdit.value = {
      ...examData,
      // 确保 courseName 字段被正确赋值
      courseName: courseData.title
    };

    // 4. 打开弹窗
    modalController.openPopup('newAssessmentModal');

  } catch (error) {
    console.error("编辑考核时数据加载失败:", error);
    ElMessage.error("加载编辑数据失败，请稍后重试。");
  }
};


const searchForm = reactive({
  name: "",
  type: "",
  status: "",
});
// 添加刷新方法
const refreshTable = () => {
  if (userStore.user && userStore.user.name) {
    examStore.fetchExams({ pageNum: 1, pageSize: 10, creatorName: userStore.user.name });
  }
};
const assessments = computed(() => {
  console.log("assessments (from teacher_myExam):", userStore.teacher_myExam);
  // 确保 userStore.teacher_myExam 是一个数组，如果不是则返回空数组
  return Array.isArray(userStore.teacher_myExam)
    ? userStore.teacher_myExam
    : [];
});

const currentPage = ref(1);
const pageSize = ref(10);

const filteredAssessments = computed(() => {
  return assessments.value.filter((item) => {
    const nameMatch =
      !searchForm.name || item.exam.title.includes(searchForm.name);
    const typeMatch =
      !searchForm.type || item.exam.examType === searchForm.type;
    const statusMatch =
      !searchForm.status || item.exam.status === searchForm.status;
    return nameMatch && typeMatch && statusMatch;
  });
});

const navigateToQuestions = (examId) => {
  if (!examId) {
    ElMessage.error("无效的考核ID");
    return;
  }
  // 跳转到新的路由，并通过路径参数传递 examId
  router.push(`/teacher/exam-questions/${examId}`);
};

const paginatedAssessments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredAssessments.value.slice(start, end);
});

// const totalAssessments = computed(() => assessments.value.length);
const totalAssessments = computed(() => examStore.total);
// 新增：计算状态为“草稿”的考核数量
// const draftAssessmentsCount = computed(() => {
//   if (!exams.value) {
//     return 0;
//   }
//   return exams.value.filter(item => item.exam.status === 'draft').length;
// });
const averagePassRate = ref(0); // 用于存储计算出的平均通过率
const getStatusType = (status) => {
  switch (status) {
    case "published":
      return "success"; // 已发布
    case "draft":
      return "warning"; // 草稿
    default:
      return "info";
  }
};

const onSearch = () => {
  currentPage.value = 1;

  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    creatorName: userStore.user.name, // 创建人
  };

  // 添加过滤条件
  if (searchForm.name) {
    params.keyword = searchForm.name;
  }
  if (searchForm.type) {
    params.examSectionName = searchForm.type;
  }
  if (searchForm.status) {
    params.status = searchForm.status;
  }

  examStore.fetchExams(params);
};

// 新增：计算并设置通过率的函数
const calculateAndSetPassRate = () => {
  // 1. 先获取当前教师创建的所有考核的 ID
  const teacherExamIds = new Set(
    (teacherExams.value || []).map(e => e.exam.id)
  );

  if (teacherExamIds.size === 0) {
    averagePassRate.value = 0;
    return;
  }

  // 2. 获取所有学生的答卷
  examStore.fetchAllSubmissions((allSubmissions) => {
    // 3. 筛选出属于该教师的、且已完成的答卷
    console.log("allSubmissions:", allSubmissions);
    const relevantSubmissions = allSubmissions.filter(sub =>
      teacherExamIds.has(sub.examSubmission.examId) &&
      sub.examSubmission.gradingStatus === 'completed'
    );

    if (relevantSubmissions.length === 0) {
      averagePassRate.value = 0;
      return;
    }

    // 4. 在筛选出的答卷中，计算通过的数量
    const passedCount = relevantSubmissions.filter(sub =>
      sub.examSubmission.totalScore >= 60
    ).length;

    // 5. 计算通过率并更新 ref
    const rate = (passedCount / relevantSubmissions.length) * 100;
    averagePassRate.value = rate.toFixed(1); // 保留一位小数
  });
};

const onReset = () => {
  searchForm.name = "";
  searchForm.type = "";
  searchForm.status = "";
  currentPage.value = 1;
  // In a real application, you would re-fetch data from the backend here
  examStore.fetchExams({
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    creatorName: userStore.user.name,
  });
};

// const handleEdit = async (row) => {
//   await userStore.updateExam(row.exam);
//   ElMessage.info(`编辑考核: ${row.exam.title}`);
//   // Implement edit logic, e.g., open a dialog with row data
// };

const handleDelete = (row) => {
  examStore.deleteExam(row.exam.id, () => {
    // 删除成功后，重新获取数据以刷新列表
    refreshTable();
  });
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  console.log(`${val} items per page`);
};

const handlePageChange = (val) => {
  currentPage.value = val;
  if (userStore.user && userStore.user.name) {
    examStore.fetchExams({ pageNum: val, pageSize: 10, creatorName: userStore.user.name });
  }
};

const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
</script>

<style scoped>
.stats-card {
  .bi {
    font-size: 2.5rem;
  }
}

.search-input {
  max-width: 250px;
}

.el-pagination {
  justify-content: flex-end;
}

.assessment-card {
  .card-header {
    background-color: var(--el-fill-color-light);
    padding: 10px 20px;
    border-bottom: 1px solid var(--el-border-color-light);
    border-radius: var(--el-border-radius-base) var(--el-border-radius-base) 0 0;
  }
}
</style>
